package cn.onepiece.smili.service.impl;

import java.io.File;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.wht.pirates.result.Result;

import cn.onepiece.smili.render.RenderService;
import cn.onepiece.smili.render.handler.TableHandler;
import cn.onepiece.smili.render.info.TableInfo;
import cn.onepiece.smili.service.SmiliService;

/**
 * @Author: haoting.wang
 * @Date: Created in 下午1:29 2017/5/27
 */
@Service
public class SmiliServiceImpl implements SmiliService {

    private static Logger logger = LoggerFactory.getLogger(SmiliServiceImpl.class);

    @Autowired
    private DataSource    dataSource;

    @Autowired
    private RenderService tableRenderService;

    @Override
    public void generator(String[] tNames, String basePackage, File generatorDir) {

        //1、获取数据库连接
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        //2、获取元数据
        DatabaseMetaData metaData = TableHandler.getDatabaseMetaData(connection);
        if (metaData == null) {
            throw new RuntimeException("metaData 获取失败");
        }

        List<TableInfo> tableInfoList = Lists.newArrayList();

        //3、解析元数据
        for (String tName : tNames) {
            TableInfo tableInfo = TableHandler.parseResultSet(metaData, tName);
            tableInfo.setBasePackage(basePackage);
            tableInfoList.add(tableInfo);
        }

        String savePath = basePackage.replaceAll("\\.", "/");
        savePath = generatorDir.getPath() + "/" + savePath;

        //4、渲染
        for (TableInfo tableInfo : tableInfoList) {
            tableRenderService.exportModel(tableInfo, savePath);
            tableRenderService.exportDto(tableInfo, savePath);
            tableRenderService.exportMapper(tableInfo, savePath);
            tableRenderService.exportMapperXml(tableInfo, savePath);
            tableRenderService.exportService(tableInfo, savePath);
            tableRenderService.exportServiceImpl(tableInfo, savePath);
            tableRenderService.exportController(tableInfo, savePath);
            tableRenderService.exportHtml(tableInfo, savePath);

        }
    }
}
